<?php
namespace App\Admin\Controllers\Quality;

use App\Importer\Quality\QuImporter;
use App\Models\Basics\SysCountry;
use App\Models\Basics\SysICountry;
use App\Models\Product\ProductAmazonSku;
use App\Models\Product\ProductClassify;
use App\Models\Product\ProductSku;
use App\Models\Quality\QComplaint;
use App\Util\RExcel;
use Encore\Admin\Controllers\AdminController;
use Encore\Admin\Facades\Admin;
use Illuminate\Support\Facades\DB;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;
use Maatwebsite\Excel\Facades\Excel;
use Symfony\Component\HttpFoundation\File\UploadedFile;
class ComplaintUploadController extends AdminController{

    protected $title = '客诉管理上传';

    protected function grid()
    {
        return view("quality.complaint.upload.index");
    }

    public function upload(Request $request){
        $file = $request->file('source_file');
        if ($file->isValid()) {
            $re = $this->_importFile($file);
            if(is_array($re)) {
                if($re['flag']){
                    admin_toastr('文件：'.$re['data'].' 上传成功！');
                }else{
                    admin_toastr($re['data'],'error');
                }
            }else{
                return $re;
            }
        }else{
            admin_toastr('无效文件！','error');
        }
        return back()->withInput();
    }

    private function _importFile(UploadedFile $file){
        try{
            $data = Excel::toArray(new QuImporter(),$file);
            $data = $data[0];
            if(!$data)return ['flag' => false,'data' => '请上传包含有数据的文件！'];
            DB::beginTransaction();
            $errors = [];
            $count = 1;
            $userId = Admin::user()->id;
            foreach($data as $row){
                $count++;
                $reportDate = $row[0] ? RExcel::toDateTime(trim($row[0])) : '';
                $_country = $row[1] ? trim($row[1]) : '';
                $_origin = $row[2] ? trim($row[2]) : '';
                $orderNo = $row[3] ? trim($row[3]) : null;
                $sellerSku = $row[4] ? trim($row[4]) : null;
                $asin = $row[5] ? trim($row[5]) : null;
                $sku = $row[6] ? trim($row[6]) : null;
                $classify = $row[7] ? trim($row[7]) : null;
                $content = $row[8] ? str_replace(["\r","\n","\r\n"],'',trim($row[8])) : null;
                if(!$reportDate || !$_country || !$_origin || !$content){
                    $errors[$count] = '必填项为空';
                    continue;
                }
                $country = strtoupper($_country);
                $countryId = SysCountry::getIdByCountry($country);
                if(!$countryId){
                    $errors[$count] = $_country.'系统不存在';
                    continue;
                }
                $areaId = SysICountry::getAreaIdByCountryId($countryId);
                if(!$areaId){
                    $errors[$count] = $_country.'系统不存在对应站点';
                    continue;
                }
                $origin = ucfirst($_origin);
                if(!in_array($origin,QComplaint::$_origin)){
                    $errors[$count] = $_origin.'来源不存在，请选择'.implode('、',QComplaint::$_origin);
                    continue;
                }
                $originId = array_search($origin,QComplaint::$_origin);
                if($sellerSku){
                    $pas = ProductAmazonSku::query()
                        ->where('country_id',$countryId)
                        ->where('seller_sku',$sellerSku)
                        ->first();
                    if(!$pas){
                        $errors[$count] = $_country.'_'.$sellerSku.'亚马逊产品列表不存在';
                        continue;
                    }
                    $pSkuId = $pas->psku_id;
                    $ps = ProductSku::getModelById($pas->psku_id);
                    $classifyId = $ps->classify_id;
                }elseif($asin){
                    $pas = ProductAmazonSku::query()
                        ->where('country_id',$countryId)
                        ->where('child_asin',$asin)
                        ->first();
                    if(!$pas){
                        $errors[$count] = $_country.'_'.$asin.'亚马逊产品列表不存在';
                        continue;
                    }
                    $pSkuId = $pas->psku_id;
                    $ps = ProductSku::getModelById($pas->psku_id);
                    $classifyId = $ps->classify_id;
                }elseif($sku){
                    $ps = ProductSku::getModelByCode($sku);
                    if(!$ps){
                        $errors[$count] = $sku.'产品不存在';
                        continue;
                    }
                    $pSkuId = $ps->id;
                    $classifyId = $ps->classify_id;
                }elseif($classify){
                    $classifyId = ProductClassify::getIdByTitle($classify);
                    if(!$classifyId){
                        $errors[$count] = $classify.'品类不存在';
                        continue;
                    }
                    $pSkuId = null;
                }else{
                    $errors[$count] = '平台SKU，ASIN，产品SKU，品类不能同时为空';
                    continue;
                }
                $query = QComplaint::query()->where('content',$content);
                if($pSkuId){
                    $query->where('psku_id',$pSkuId);
                }elseif($classifyId){
                    $query->where('classify_id',$classifyId);
                }
                $count = $query->count();
                if($count > 0){
                    $errors[$count] = '重复添加';
                    continue;
                }
                QComplaint::create([
                    'report_date' => $reportDate,
                    'origin' => $originId,
                    'order_no' => $orderNo,
                    'area_id' => $areaId,
                    'country_id' => $countryId,
                    'seller_sku' => $sellerSku,
                    'asin' => $asin,
                    'psku_id' => $pSkuId,
                    'classify_id' => $classifyId,
                    'content' => $content,
                    'operator_id' => $userId
                ]);
            }
            DB::commit();
            if(empty($errors)){
                return ['flag' => true,'data' => $file->getClientOriginalName()];
            }else{
                return RExcel::importResult($errors);
            }
        }catch(\Exception $e){
            DB::rollBack();
            report($e);
            return ['flag' => false,'data' => '系统异常！'];
        }
    }

    public function template(Request $request){
        $temp = $request->get('temp');
        $suffix = $request->get('suffix','xlsx');
        return Storage::disk('admin')->download("template/{$temp}-template.{$suffix}");
    }
}
